package com.transaction.simulate.config;

import com.auth0.jwt.interfaces.Claim;
import com.transaction.common.util.JwtTokenUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@Component
public class RequestInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException {
        String authorization = request.getHeader("Authorization");
        //检验请求地址
        String requestURI = request.getRequestURI();
        //获取用户请求头携带的用户信息
        logger.info("每个请求的地址{},请求携带的token为{}",requestURI,authorization);
        if(authorization == null){
            response.sendError(401);
            return false;
        }else{
            //验证token是否是该项目的token,不是回到登录页面
            Map<String, Claim> verifyResult =  JwtTokenUtil.verifyToken(authorization,JwtTokenUtil.SIMULATE_SECRET);
            if(CollectionUtils.isEmpty(verifyResult)){
                response.sendError(401);
                return false;
            }
            logger.info("验证token结果为:userCode:{}", ((Claim)MapUtils.getObject(verifyResult,"userCode")).asString());
            //TODO 这里可以校验权限，如果权限不足，不进行后续操作（该项目控制到菜单，没有精确到请求）
//            response.sendError(403);
//            return false;
        }
        return true;
    }
}
